package com.huafeng.api;

import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONUtil;
import com.huafeng.config.OpenAiConfig;
import com.huafeng.entity.openai.Request;
import com.huafeng.entity.openai.Response;
import com.huafeng.utils.SpringContextUtils;
import org.springframework.aop.scope.ScopedProxyUtils;

/**
 * @author 花风
 * @date 2023/4/12 23:02
 * @Description 调用openAI的接口
 */
public class OpenAiApi {
    private static final OpenAiConfig openAiConfig = SpringContextUtils.getBean(OpenAiConfig.class);

    private static final String apiKey = openAiConfig.getApiKey();

    private static final String model = openAiConfig.getModel();

    public static Response doAnswer(String message){
        Request request = new Request();
        request.setPrompt(message);
        request.setModel(model);
        request.setTemperature(0);
        request.setMax_tokens(1024);

        String url = "https://api.openai.com/v1/completions";
        String body = HttpRequest.post(url)
                .header("Authorization", "Bearer" + apiKey)
                .body(JSONUtil.toJsonStr(request))
                .execute()
                .body();
        return JSONUtil.toBean(body,Response.class);
    }
}
